package com.atguigu.gmall.listener;

import com.atguigu.gmall.rabbit.constant.RabbitConst;
import com.atguigu.gmall.service.SearchService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Configuration
public class MessageReceiver {


    @Autowired
    private SearchService searchService;

    //监听上架
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConst.QUEUE_GOODS_UPPER,autoDelete = "false"),
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_GOODS,autoDelete = "false"),
            key={RabbitConst.ROUTING_GOODS_UPPER}
    ))
    public void receiverMessageUpper(Long skuId,Message message, Channel channel) throws IOException {
        try{

            searchService.upperGoods(skuId);
            //false确定一个消息,true批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            e.printStackTrace();
                if(message.getMessageProperties().getRedelivered()) {
                    System.out.println("消息已重复处理,拒绝再次接收");
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                }else{
                    System.out.println("消息即将再次返回队列处理");
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                }
        }
    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConst.QUEUE_GOODS_LOWER,autoDelete = "false"),
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_GOODS,autoDelete = "false"),
            key={RabbitConst.ROUTING_GOODS_LOWER}
    ))
    public void receiverMessageLower(Long skuId,Message message, Channel channel) throws IOException {
        try{
            searchService.lowerGoods(skuId);
            //false确定一个消息,true批量确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){

            if(message.getMessageProperties().getRedelivered()) {
                System.out.println("消息已重复处理,拒绝再次接收");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }else{
                System.out.println("消息即将再次返回队列处理");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }

}
